<?php
/**
 * 业主管理
 * @author Administrator
 *
 */
class ownerManage extends CControllerManageBase{
	public function show()
	{
		$model = new ownerModel();
		$pageIndex = $this->getRequestData("page","GET",1);
		$pageSize = 10;
		$c = 0;
		$pay_status = $this->getRequestData("sel_pay_status","get","-1");
		$card_status = $this->getRequestData("sel_card_status","get","-1");
		$card = $this->getRequestData("txt_card","get");
		$owner_name = $this->getRequestData("txt_owner_name","get");
		$community_name = $this->getRequestData("txt_community_name","get");
		
		$urlParam = array();
		$where = "o.community_id=c.community_id and o.del_flag=0 and c.del_flag=0";
		
		$cids = $this->getUserCommunityID();
		
		if($cids)
		{
			$where .= " and c.community_id in (".$cids.")";
		}
		
		if($card_status!="-1")
		{
			$where .= " and card_status=".$card_status."";
			
			$urlParam["sel_card_status"] = $card_status;
		}
		
		if($pay_status!="-1")
		{
			$where .= " and pay_status=".$pay_status."";
			
			$urlParam["sel_pay_status"] = $pay_status;
		}
		
		if($card)
		{
			$where .= " and supplementary_card='".$card."'";
			
			$urlParam["txt_card"] = $card;
		}
		
		if($owner_name)
		{
			$where .= " and owner_name='".$owner_name."'";
			
			$urlParam["txt_owner_name"] = $owner_name;
		}
		
		if($community_name!="")
		{
			$where .= " and c.community_name='".$community_name."'";
			
			$urlParam["txt_community_name"] = $community_name;
		}
		
		$this->setViewParam("card_status", $card_status);
		$this->setViewParam("pay_status", $pay_status);
		$this->setViewParam("card", $card);
		$this->setViewParam("owner_name", $owner_name);
		$this->setViewParam("community_name", $community_name);
		
		//$cList = $model->selectDataSetByWhere("t_community","community_id,community_name",array(),"del_flag=0");
		
		//$this->setViewParam("cList", $cList);
		
		$pageUrl = $this->getUrlParam($urlParam, array("txt_card","txt_owner_name","community_name"));
		$pageUrl = $pageUrl? "?".$pageUrl:"";

		$list = $model->selectPage($pageIndex,$pageSize,"o.owner_id,o.user_name,o.owner_name,o.supplementary_card,o.phone,o.balance,o.card_status,o.pay_status,c.community_name,o.first_login",$where,"owner_id desc","",$c,"t_owner o, t_community c");
		$pageStr = CPage::showPage($pageIndex,$pageSize,$c,$pageUrl);

		$pageUrl = $pageUrl?"&page=".$pageIndex:"page=".$pageIndex;

		$this->setCssBlock(".container{min-width:1200px;}");
		$this->setMenu("业主列表");
		$this->render("owner/list",array("list"=>$list,"pageStr"=>$pageStr,"pageUrl"=>$pageUrl));
	}
	
	private function getPostInfo()
	{
		$modelInfo = array();
		
		$modelInfo["main_card"] = $this->getRequestData("txt_main_card");
		$modelInfo["supplementary_card"] = $this->getSupplementaryCard($this->getRequestData("txt_supplementary_card"));
		$modelInfo["owner_name"] = $this->getRequestData("txt_owner_name");
		$modelInfo["phone"] = $this->getRequestData("txt_phone");
		$modelInfo["id_card"] = $this->getRequestData("txt_id_card");
		$modelInfo["community_id"] = $this->getRequestData("hidCo");
		$modelInfo["address"] = $this->getRequestData("txt_address");
		$modelInfo["remark"] = $this->getRequestData("txt_remark");
		
		if(!isset($_GET["id"]))
		{
			$modelInfo["user_name"] = $modelInfo["supplementary_card"]; //新增时用户名设为卡号
			$modelInfo["create_time"] = date("Y-m-d H:i:s");
		}
		
		return $modelInfo;
	}
	
	public function add(){
		$errorStr="";
		$rule=CCustomFormValidator::ownerValidator();
		$this->formValidator->init(array("formID"=>"t_ownerForm"));
		$this->formValidator->setRules($rule);
		if($_POST){
			$modelInfo = $this->getPostInfo();
			$idCard = $modelInfo["id_card"];
			$pwdStr = substr($idCard,strlen($idCard)-6);
			$modelInfo["user_pwd"] = CCommon::pwdMd5($pwdStr);
			$modelInfo["pay_pwd"] = CCommon::pwdMd5("000000");
			$error = $this->formValidator->run();
			if($error){
				$errorStr = "<div><ul>";
				foreach ($error as $item){
					$errorStr .= "<li>".$item."</li>";
				}
				$errorStr .= "</ul></div>";
			}
			else{
				$model=new ownerModel();
				$uid=$model->insert($modelInfo);
				
				if($uid>0)
				{
					$this->sysMsg("新增成功",0,array(array("text"=>"返回业主列表","href"=>$this->_manageDomain."ownerManage/show/"),array("text"=>"继续新增","href"=>$this->_manageDomain."ownerManage/add/")));
				}
				else
				{
					$this->sysMsg("新增失败",1);
				}
			}
		}

		$this->setJsBlock("init();_changeSelCallBack=true;");
		$this->setStyleFile("/css/validator.css");
		$this->setJsFile(array("/js/formValidator.js","/js/formValidatorRegex.js"));
		$this->setMenu(array(array("text"=>"业主列表","href"=>$this->_manageDomain."ownerManage/show/"),array("text"=>"业主新增")));
		$this->render("owner/add",array("error"=>$errorStr));
	}

	public function edit(){
		$owner_id = $this->getRequestData("id","GET");
		$errorStr = "";

		$rule=CCustomFormValidator::ownerValidator($owner_id);
		$this->formValidator->init(array("formID"=>"t_ownerForm"));
		$this->formValidator->setRules($rule);

		$model=new ownerModel();
		if($_POST){
			$modelInfo = $this->getPostInfo();
			$modelInfo["owner_id"] = $owner_id;
			
			$error = $this->formValidator->run();
			if($error){
				$errorStr = "<div><ul>";
				foreach ($error as $item){
					$errorStr .= "<li>".$item."</li>";
				}
				$errorStr .= "</ul></div>";
			}
			else{
				$model->updateByPkId($modelInfo);

		        header("location:".$this->_manageDomain."ownerManage/show/");
		        exit();
			}
		}
		else{
			$modelInfo = $model->select($owner_id);
			if(!$modelInfo) {
				$this->sysMsg("记录不存在",1);
			}

			$province = $modelInfo["province"];
			$city = $modelInfo["city"];
			$area = $modelInfo["area"];
			$this->setJsBlock("init('".$province."','".$city."','".$area."');_changeSelCallBack=true;");
			
			$model=new communityModel();

			$clist = $model->getCommunityByArea($province, $city, $area);
			
			$chtml = "";
			foreach($clist as $item)
			{
				$chtml .= "<label for='rdCommunity".$item["community_id"]."'>"
					.$item["community_name"]."</label><input type='radio' 
					onclick='selCommunityRd(".$item["community_id"].")' 
					name='rdCommunity' id='rdCommunity".$item["community_id"]."' 
					value='".$item["community_id"]."' ";
				
				if($item["community_id"] == $modelInfo["community_id"])
				{
					$chtml .= "checked='checked' ";
				}
				$chtml .= "/>";
			}
			
			$this->setViewParam("chtml",$chtml);
		}
		
		$this->setStyleFile("/css/validator.css");
		$this->setJsFile(array("/js/formValidator.js","/js/formValidatorRegex.js"));
		$this->setMenu(array(array("text"=>"业主列表","href"=>$this->_manageDomain."ownerManage/show/"),array("text"=>"业主修改")));
		$this->render("owner/edit",array("error"=>$errorStr,"modelInfo"=>$modelInfo));
	}
	
	public function del()
	{
		$id = $this->getRequestData("id","GET");
		if ($id)
        {
            $buc = new ownerModel();

			$buc->deleteByPkId($id);
            $this->show();
        }
	}
	
	public function batchDel()
	{
		$ids = $this->getRequestData("ids","GET");
		
		$idsList = explode(",",$ids);
		
		$buc = new ownerModel();
		foreach($idsList as $id)
		{
            $buc->deleteByPkId($id);
		}
		$this->show();
	}
	
	/**
	 * 验证业主名是否存在
	 */
	public function checkCard()
	{
		$f = new CCustomFormValidator();
		$r = "";
		$id = $this->getRequestData("id","get");
		if(isset($_GET["txt_main_card"]))
		{
			$r = $f->checkMainCard($this->getRequestData("txt_main_card","get"),$id);
		}
		else if(isset($_GET["txt_supplementary_card"]))
		{
			$card = $this->getRequestData("txt_supplementary_card","get");
			if(!$id)
			{
				$card = $this->getSupplementaryCard($card);
				
				if($card==-1)
				{
					echo 0;
					exit;
				}
			}
			$r = $f->checkSupplementaryCard($card,$id);
		}
		
		echo $r?1:0;
		exit;
	}
	
	private function getSupplementaryCard($card)
	{
		if(preg_match("/^\d{1,12}$/", $card))
		{
			$l = 12-strlen($card);
			for($i=0;$i<$l;$i++)
			{
				$card = "0".$card;
			}
			return $card;
		}
		else{
			return -1;
		}
	}
	
	/**
	 * 验证业主登录名是否存在
	 */
	public function checkUserName()
	{
		$f = new CCustomFormValidator();
		$id = $this->getRequestData("id","get");
		echo $f->checkOwnerUserName($this->getRequestData("txt_user_name","get"),$id)?1:0;
		exit;
	}
	
	public function changeStatus()
	{
		$id = $this->getRequestData("id");
		$type = $this->getRequestData("type");
		
		if($type!=1 && $type!=2)
		{
			echo "-1";
			exit;
		}
		
		$ownerInfo["owner_id"] = $id;
		$ownerInfo["card_status"] = $type;
		
		$ownerModel = new ownerModel();

	    echo $ownerModel->updateByPkId($ownerInfo);
	    exit;
	}
	
	public function resetUserPwd()
	{
		$this->resetPwd("user_pwd");
	}
	
	public function resetPayPwd()
	{
		$this->resetPwd("pay_pwd");
	}
	
	public function resetPwd($type)
	{
		
		$ownerModel = new ownerModel();
		$owner_id = $this->getRequestData("id");
		
		if(!CCommon::checkNum($owner_id))
		{
			echo -1;
			exit;
		}
		
		//$pwd = "000000";
		//if($type=="user_pwd")
		//{
			$ownerInfo = $ownerModel->selectById($owner_id,"owner_id=".$owner_id,"id_card");
			
			$pwd = substr($ownerInfo["id_card"],strlen($ownerInfo["id_card"])-6);
		//}
		
		$ownerInfo["owner_id"] = $owner_id;
		$ownerInfo[$type] = CCommon::pwdMd5($pwd);
		
		echo $ownerModel->updateByPkId($ownerInfo);
		exit;
	}
	
	public function importFromExcel()
	{
		if($this->getRequestData("act","get") == "upload")
		{
			$tempFile = $_FILES["Filedata"];
			
			if($tempFile["error"]==UPLOAD_ERR_INI_SIZE || $tempFile["error"]==UPLOAD_ERR_FORM_SIZE)
			{
				$this->returnMsg("图片超出系统限制.",0);
			}
			else if($tempFile["error"]==UPLOAD_ERR_PARTIAL || $tempFile["error"]==UPLOAD_ERR_NO_FILE )
			{
				$this->returnMsg("图片上传失败,可能是网络原因,请重试.",0);
			}
	
			//判断文件大小
			$fileSize = $tempFile['size'];
			if ($fileSize>10*1024*1024)
			{
				$this->returnMsg("图片不能超过10MB.",0);
		    }
		    
		    $dir = "temp";
		    
		    //获取上传文件信息
	        $tempFileName = $tempFile['tmp_name'];
	
			$fileName = $tempFile['name'];
	
			$iNeedDate = $this->getRequestData('needdate', 'get', 0);
	                
			$filePath = "uploadfile/".$dir."/";
			if($iNeedDate){
				$filePath .= date("Ymd")."/";
			}
			
			if(!is_dir($filePath))
			{
		    	mkdir($filePath,0644,true);
			}
	
		    $pathParts = pathinfo($fileName);
		    
		    $file_ext = $pathParts['extension'];
		    
		    $newFileName = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
		    
			//获取新图片路径和文件名
			$newFile = $filePath.$newFileName;//$this->getNewPicPath($fileName,$filePath);
			
			$return = move_uploaded_file($tempFileName,$newFile);
			
			if(!$return)
			{
				$this->returnMsg("图片上传失败，请重试.",0);
			}
			
			$this->returnMsg($newFile,1);
		}
		$this->formValidator->init(array("formID"=>"t_ownerForm"));
		
		$rule = array(
			"hid_file_path"=>array(
						"formValidator"=>array("tipid"=>"hid_file_path_tip","empty"=>"false","onshow"=>"请选择文件","onfocus"=>"请选择文件","oncorrect"=>"已经上传"),
						"inputValidator"=>array("min"=>"1","onerror"=>"请上传excel文件")
				)
		);
		$this->formValidator->setRules($rule);
		if($_POST)
		{
			$filePath = $this->getRequestData("hid_file_path");
			require_once $this->_basePath.'PHPExcel/Classes/PHPExcel.php';
			
			$phpExcel = new PHPExcel();
			
			$phpReader = new PHPExcel_Reader_Excel2007();
			
			if(!$phpReader->canRead($filePath))
			{
				$phpReader = new PHPExcel_Reader_Excel5();
				
				if(!$phpReader->canRead($filePath))
				{
					$this->sysMsg("读取excel错误,请确定excel版本为2003或2007",1);
				}
			}
			
			$PHPExcel = $phpReader->load($this->_basePath.$filePath);
			/**读取excel文件中的第一个工作表*/
			$currentSheet = $PHPExcel->getSheet(0);
			/**取得最大的列号*/
			$allColumn = $currentSheet->getHighestColumn();
			/**取得一共有多少行*/
			$allRow = $currentSheet->getHighestRow();
			
			$keyList = array(
				"A"=>"main_card",
				"B"=>"supplementary_card",
				"C"=>"owner_name",
				"D"=>"phone",
				"E"=>"id_card",
				"J"=>"address"
			);
			
			$communityKeyList = array(
				"F"=>"province",
				"G"=>"city",
				"H"=>"area",
				"I"=>"community_name"
			);
			
			$model = new ownerModel();
			
			$errorList = array();
			$importNum = 0;
			/**从第二行开始输出，因为excel表中第一行为列名*/
			for($currentRow = 2;$currentRow <= $allRow;$currentRow++){
				/**从第A列开始输出*/
				$modelInfo = array();
				$cModelInfo = array();
				for($currentColumn= 'A';$currentColumn<= $allColumn; $currentColumn++){
					$val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue();/**ord()将字符转为十进制数*/
					
					if(key_exists($currentColumn,$keyList))
					{
						$modelInfo[$keyList[$currentColumn]] = $val;
					}
					else if(key_exists($currentColumn,$communityKeyList)){
						$cModelInfo[$communityKeyList[$currentColumn]] = $val;
					}
				}
				
				$check = true;
				foreach($keyList as $key=>$v)
				{
					if(isset($modelInfo[$v]))
					{
						if(!$modelInfo[$v])
						{
							$check = false;
						}
					}
					else{
						$check = false;
					}
				}
				
				if(!$check)
				{
					$modelInfo["error"] = "数据不完整";
					$errorList[] = $modelInfo+$cModelInfo;
					continue;
				}
				
				if(preg_match("/^[\\d]{12}$/",$modelInfo["supplementary_card"])<=0)
				{
					$modelInfo["error"] = "附属卡卡号必须为12位数字";
					$errorList[] = $modelInfo+$cModelInfo;
					continue;
				}
				
				if($model->checkCard($modelInfo["supplementary_card"],"supplementary_card"))
				{
					$modelInfo["error"] = "附属卡卡号或用户名已经存在";
					$errorList[] = $modelInfo+$cModelInfo;
					continue;
				}
				$cInfo = $model->selectByWhere("t_community", "community_id",$cModelInfo);
				if(!$cInfo)
				{
					$modelInfo["error"] = "社区不存在或社区不在指定地域";
					$errorList[] = $modelInfo+$cModelInfo;
					continue;
				}
				$modelInfo["community_id"] = $cInfo["community_id"];
				$modelInfo["user_name"] = $modelInfo["supplementary_card"];
				$pwdStr = substr($modelInfo["id_card"],strlen($modelInfo["id_card"])-6);
				$modelInfo["user_pwd"] = CCommon::pwdMd5($pwdStr);
				$modelInfo["pay_pwd"] = CCommon::pwdMd5("000000");
				$modelInfo["create_time"] = date("Y-m-d H:i:s");
				
				$id = $model->insert($modelInfo);
				if($id)
				{
					$importNum++;
				}
			}
			
			if($errorList)
			{
				$this->setMenu(array(array("text"=>"业主列表","href"=>$this->_manageDomain."ownerManage/show/"),array("text"=>"业主批量导入","href"=>$this->_manageDomain."ownerManage/importFromExcel"),array("text"=>"导入结果")));
				$this->render("owner/import_result",array("list"=>$errorList, "improtNum"=>$importNum,"errorNum"=>count($errorList)));
			}
			else{
				$this->sysMsg("导入完成",0,array(array("text"=>"返回业主列表","href"=>$this->_manageDomain."ownerManage/show/")));
			}
			
			exit;
		}
		
		$this->setStyleFile("/css/validator.css");
		$this->setJsFile(array("/js/formValidator.js","/js/formValidatorRegex.js",$this->_imgDomain."uploadify/swfobject.js",$this->_imgDomain."uploadify/jquery.uploadify.v2.1.0.min.js"));
		$this->setJsBlock("initSwfUpload();");
		$this->setMenu(array(array("text"=>"业主列表","href"=>$this->_manageDomain."ownerManage/show/"),array("text"=>"业主批量导入")));
		$this->render("owner/import");
	}
	
	private function returnMsg($msg,$type)
	{
		echo $type.",".$msg;
		exit;
	}
}